﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using System.Linq;

namespace Core.AutoFac
{
    public static class AutoFacExtentions
    {
        /// <summary>
        /// 构造AutofacContainer接管MS自带的容器
        /// </summary>
        /// <param name="builder"></param>
        public static void RegisterContainer(this ContainerBuilder builder)
        {
            var dlls = App.App.GetDlls();
            foreach(var dll in dlls)
            {
                builder.RegisterAssemblyTypes(dll).Where(r => !r.IsAbstract && typeof(IAutoInject).IsAssignableFrom(r)).AsImplementedInterfaces();
                builder.RegisterAssemblyTypes(dll).Where(r => !r.IsAbstract && typeof(IFilterMetadata).IsAssignableFrom(r)).PropertiesAutowired();
            }
            builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().AsImplementedInterfaces();
        }
        /// <summary>
        /// 接管容器
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IHostBuilder UseAutoProviderFactory(this IHostBuilder builder)
        {
            return builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
        }
    }
}
